package zzz.icexxx.scan_file_by_time;

import java.io.File;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

import cn.hutool.core.util.StrUtil;

public class FileScan {
    private static List<FileInfo> list = new ArrayList<FileInfo>();
    private static List<FileInfo> listFolder = new ArrayList<FileInfo>();

    public static void scan(String file, String fileName) {
        scan(new File(file), fileName);
        Comparator<FileInfo> c = Comparator.comparing(FileInfo::getUpdateTime).reversed();
        list.sort(c.reversed());
        print(list, 10);
        System.out.println("================");
        print(listFolder, 10);
    }

    private static void print(List<FileInfo> list, int limit) {
        for (int i = 0; i < list.size(); i++) {
            FileInfo fileInfo = list.get(i);
            String fullName = fileInfo.getFullName();
            long size = fileInfo.getSize();
            System.out.println("\t " + size + "\t " + fullName);
        }
    }

    private static void scan(File folder, String fileName) {
        if (folder.isDirectory()) {
            File[] listFiles = folder.listFiles();
            for (File file : listFiles) {
                scan(file, fileName);
            }
        } else {
            String name = folder.getName();
            String simple = StrUtil.subBefore(name, ".", true);
            if (name != null && name.equals(fileName)) {
                FileInfo fileInfo = new FileInfo();
                String absolutePath = folder.getAbsolutePath();
                long length = folder.length();
                long updateTime = folder.lastModified();
                fileInfo.setFileName(name);
                fileInfo.setFullName(absolutePath);
                fileInfo.setSize(length);
                fileInfo.setUpdateTime(updateTime);
                list.add(fileInfo);
                File file = new File(folder.getParent(), simple);
                if (file.exists() && file.isDirectory()) {
                    absolutePath = file.getAbsolutePath();
                    fileInfo = new FileInfo();
                    fileInfo.setFileName(simple);
                    fileInfo.setFullName(absolutePath);
                    listFolder.add(fileInfo);
                }
            }
        }
    }

}
